package com.hc.sort.utils;

import java.sql.*;
public class JdbcUtil {
    //private static String url ="jdbc:mysql://localhost:3306/mynews";

    //解决乱码的问题
    private static String url ="jdbc:mysql://localhost:3306/bank?useUnicode=true&serverTimezone=UTC&characterEncoding=UTF-8";
    private static String userName ="root";
    private static String password ="123456";
    //静态代码块，在类加载时候执行，只会执行一次
    static {
        try {
            //1、加载驱动，交给DriverManager管理
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    //获取connection
    public static Connection getConnection(){
        //Class.forName("com.mysql.jdbc.Driver");//放这里是有问题的。
        try {
            return DriverManager.getConnection(url,userName,password);
        }catch (SQLException ex){
            ex.printStackTrace();
            return null;
        }
    }

    public static void close(Connection conn){
        try {
            if(conn !=null)
                conn.close();
        }catch(SQLException ex){
            ex.printStackTrace();
        }
    }

    public static void close(Statement stmt){
        try {
            if(stmt !=null)
                stmt.close();
        }catch(SQLException ex){
            ex.printStackTrace();
        }
    }

    public static void close(ResultSet rs){
        try {
            if(rs !=null)
                rs.close();
        }catch(SQLException ex){
            ex.printStackTrace();
        }
    }

    public static void close(ResultSet rs,Statement stmt,Connection conn){
        close(rs);
        close(stmt);
        close(conn);
    }

    public static void main(String[] args)throws Exception {
        Connection conn = getConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select * from t_business_type");
        while(rs.next()){
            System.out.println(rs.getString("bt_name"));
        }
        close(rs,stmt,conn);
    }
}
